<!DOCTYPE html>
<html lang="zh">

	<head>
		<meta charset="UTF-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>室内定位</title>
		<link rel="stylesheet" href="lib/bootstrap.min.css">
		<link rel="stylesheet" href="css/style.css">
		<script src="https://lib.baomitu.com/socket.io/2.0.1/socket.io.js"></script>
		<script src="js/math.js" type="text/javascript" charset="utf-8"></script>

	</head>

	<body>
		<div id="fengMap"></div>
		<div id="description"></div>
		<!-- 视角按钮组 -->
		<div class="viewmode-group btn-group-vertical" data-toggle="buttons">
			<button class="btn btn-default">2D</button>
			<button class="btn btn-default btn-primary">3D</button>
		</div>

		<script src="lib/jquery-2.1.4.min.js"></script>
		<script src="lib/fengmap.min.js"></script>
		<script>
			var newCoord = {
				x: 0,
				y: 0
			}
			var locationCount = 0;

			function getQueryString(name) {
				var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
				var r = window.location.search.substr(1).match(reg);
				if(r != null) return unescape(r[2]);
				return null;
			}
			//获取版本号,设置title
			document.title = '室内定位' + fengmap.VERSION;

			//定义全局map变量
			var map;
			var fmapID = 'location-test';
			var locationMarker;
			//楼层ID
			var lastGid = null;
			//第一人称、第三人称控制开关；定位跟随开关
			var others = true;
			var getData = {
				x: 14,
				y: 2
			}
			var layer = null
			var resultData = CoordTransform(getData)

			//起点终点坐标
			var points = [{
					'x': 13028213.4785,
					'y': 4737008.7298,
					groupID: 1
				},
				{
					x: 12961699.79823795,
					y: 4861826.46384646,
					groupID: 6
				}
			];
			window.onload = function() {
				//获取当前窗口的路径
				var pathOpenid = getQueryString('openId');
				console.log('pathOpenid', pathOpenid)
				$('#description').html('<p>openId：' + pathOpenid + ' </p>');
				map = new fengmap.FMMap({
					//渲染dom
					container: document.getElementById('fengMap'),
					//地图数据位置
					mapServerURL: './data/' + fmapID,
					//主题数据位置
					mapThemeURL: 'data/theme/',
					//设置主题
					defaultThemeName: '2001',
					// 默认比例尺级别设置为20级
					defaultMapScaleLevel: 22,
					//开启2维，3维切换的动画显示
					viewModeAnimateMode: true,
					//方向枚举型。可设置正南、正北、正东、正西、东南、西南等方向值。具体可参考fengmap.ControlsPoseEnum类。NORTH WEST SOUTH
					defaultControlsPose: fengmap.FMDirection.NORTH,
					defaultViewMode: fengmap.FMViewMode.MODE_2D, //初始二维还是三维状态，三维状态为MODE_3D,

					//开发者申请应用下web服务的key
					key: '670072019dff394f3f991e88e98024d5',
					//开发者申请应用名称
					appName: 'innerMap',
				});

				//打开Fengmap服务器的地图数据和主题
				map.openMapById(fmapID);

				//显示指北针
				map.showCompass = true;
				//地图加载完成回调
				map.on('loadComplete', function() {
					WebSocketTest();

					addlocationMarker(points[0])
				});

				var aBtn = document.querySelectorAll('.btn');
				//开启2维模式
				aBtn[0].onclick = function() {
					//设置地图为2维模式
					map.viewMode = fengmap.FMViewMode.MODE_2D;
					this.classList.add('btn-primary');
					aBtn[1].classList.remove('btn-primary');
				};

				//开启3维模式
				aBtn[1].onclick = function() {
					//设置地图为3维模式
					map.viewMode = fengmap.FMViewMode.MODE_3D;
					this.classList.add('btn-primary');
					aBtn[0].classList.remove('btn-primary');
				};

				//添加定位点图层
				function addlocationMarker(coord) {
					locationMarker = new fengmap.FMLocationMarker({
						//设置图片的路径
						url: 'image/pointer.png',
						//设置图片显示尺寸
						size: 46,
						//设置图片高度
						height: 1,
					});
					//添加定位点标注
					map.addLocationMarker(locationMarker);
					//设置定位图标位置
					setLocationMakerPosition(coord);
					return locationMarker;
				};

				//设置图片标注点位置信息
				function setLocationMakerPosition(coord, angle, direction) {
					var data = {
						//设置定位点的x坐标
						x: coord.x,
						//设置定位点的y坐标
						y: coord.y,
						//设置定位点所在楼层
						groupID: coord.groupID,
						time: .50,
						callback: function() {
							//回调函数
						},
						zOffset: 1
					};
					//设置定位图标旋转角度
					if(direction) {
						locationMarker.rotateTo(-direction);
						if(others) {
							map.rotateTo({
								to: direction,
								time: 1
							});
						}
					}
					//不同楼层
					if(lastGid !== coord.groupID) {
						lastGid = coord.groupID;
						locationMarker.setPosition(data);
					}
					locationMarker.moveTo(data);
					map.moveTo({
						x: coord.x,
						y: coord.y,
						groupID: coord.groupID,
						time: 1
					});
				}

				// websocketState 0:可以连接 1：小程序端断开 2：代码错误需要重连
				var websocketState = 0;
				function WebSocketTest() {
					if("WebSocket" in window) {
						var ws = new WebSocket("wss://www.dowino2o.net:8087/api/websocket?openId=map" + pathOpenid);
//						var ws = new WebSocket("wss://www.dowino2o.net:8087/api/websocket?openId=map12");
						ws.onopen = function() {
							if(websocketState == 2) {
								ws.send("reconnect");
							};
							setInterval(function() {
								// Web Socket 已连接上，使用 send() 方法发送数据
								ws.send("ping");
							}, 50000)
						};

						ws.onmessage = function(evt) {
							var received_msg = evt.data;
							console.log('收到消息：', received_msg);
							if(received_msg != '连接成功') {
								if(received_msg == 'closeMap') {
									websocketState = 1;
									ws.close();
								} else {
									try {
										var jsonObj = JSON.parse(received_msg);
										if(jsonObj.movementState == 1) {
											newCoord = {
												'x': jsonObj.pointX,
												'y': jsonObj.pointY
											}
										} else if(jsonObj.movementState == 0) {
											if(locationCount < 1) {
												newCoord = {
													'x': jsonObj.pointX,
													'y': jsonObj.pointY
												}
											}
											locationCount++;
										}

										var direction = jsonObj.alpha;
										if(direction >= 360) {
											direction -= 360
										}
										//转换后的地图坐标
										var mapCoord = CoordTransform(newCoord);
										setLocationMakerPosition(mapCoord, null, direction);
									} catch(err) {}
								}
							}
						};

						ws.onclose = function() {
							// 关闭 websocket
							console.log('连接已关闭')
							if(websocketState != 1) {
								websocketState = 2;
								WebSocketTest();
							}
						};
					} else {
						// 浏览器不支持 WebSocket
						alert("您的浏览器不支持 WebSocket!");
					}
				}
			};

			function CoordTransform(Coord) {
				//创建转换器
				var trasformer = new fengmap.MapCoordTransform();
				//来至定位系统的参数 定位的原点坐标 已经定位的范围,(矩形对角线的2个点)
				var locOrigion = {
					'x': 0,
					'y': 0
				}; //定位坐标原点
				var locRange = {
					'x': 32.387,
					'y': 32.202
				}; //定位范围

				//根据定位四个角点的地图坐标点
				var mapParas = [];
				mapParas[0] = {
					'x': 13028246.2666,
					'y': 4737041.5179
				}; //定位原点地图坐标
				mapParas[1] = {
					'x': 13028214.5795,
					'y': 4737041.5179
				}; //X轴终点地图坐标
				mapParas[2] = {
					'x': 13028214.5702,
					'y': 4737009.6396
				}; //定位原点对角点地图坐标
				mapParas[3] = {
					'x': 13028246.2666,
					'y': 4737009.6302
				}; //Y轴终点地

				//转换器初始化
				trasformer.init(locOrigion, locRange, mapParas);

				//定位系统中的定位坐标
				var loc = {
					'x': Coord.x,
					'y': Coord.y
				}; //定位系统所返回的坐标点

				//转换后的地图坐标
				var mapCoord = trasformer.transform(loc);
				return mapCoord;
			}
		</script>
	</body>

</html>